<template>
  <div>
    <h4>课程配置</h4>
    <el-form size="default" :inline="true">
      <el-form-item label="选择团队组">
        <el-select v-model="teamusergroupid" clearable placeholder="请选择" style="width: 220px">
          <el-option v-for="item in selectGroup" :key="item.name" :label="item.name" :value="item.ID">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="start" type="primary" size="default">搜索</el-button>
      </el-form-item>
    </el-form>
    <el-form>
      <el-form-item>
        <el-button :disabled="disabled" @click="setCourse" type="primary" size="default">设置课程</el-button>
      </el-form-item>
    </el-form>
    <div>
      <el-table height="71vh" style="width: 100%" :data="tableData" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="name" label="团队成员" :formatter="({ user }) => user.name" width="200"></el-table-column>
        <el-table-column prop="teamusergroupid" label="分组"
          :formatter="({ teamusergroupid }) => formatGroupName(teamusergroupid)" width="100"></el-table-column>
        <el-table-column show-overflow-tooltip prop="teamusergroupid" label="团队创建者" width="200">
          <template #default="{ row }">
            {{ teamInfo?.user?.name }}
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip prop="teamusergroupid" label="课程" :formatter="formatCourseGroup">
        </el-table-column>
      </el-table>
      <el-pagination class="pager" @current-change="pageChg" :page-size="Number(limit)" layout="total,prev, pager, next"
        :total="count">
      </el-pagination>
    </div>
    <!-- 弹窗 具体课程 -->
    <el-dialog title="课程配置" v-model="courseCfgDialogVisible" min-width='60vw' width='60vw' :before-close="close"
      top="0">
      <template #header>
        <span class="icon-text el-dialog__header-title">
          <el-icon class="text-primary">
            <Guide />
          </el-icon>
          课程配置
        </span>
      </template>
      <div class="container-box">
        <el-form label-position="top" label-width="210px" size="default">
          <el-form-item label="成员">
            <el-text siez="default" type="primary" v-for="(v, k) in multipleSelection" :key="k">
              {{ v.user?.name }}{{ k == multipleSelection.length - 1 ? "" : "、" }}
            </el-text>
          </el-form-item>
        </el-form>
        <div class="container-content">
          <div>
            <el-form label-position="top" label-width="210px" size="default">
              <el-form-item label="配置团队成员可见课程:">
                <el-checkbox-group v-model="courses" size="default">
                  <br>
                  <div class="form-item" v-for="(v, k) in courseGroup" :key="k">
                    <el-checkbox class="form-item-check-box" :label="v.ID">{{ v.label }}</el-checkbox>
                    <div class="desc cursor-pointer" @mouseenter="showCourseList(v.ID)">
                      <span> {{ v.desc }} </span>
                    </div>
                    <div class="btn-box">
                      <!-- <el-button type='primary' link @click="showCourse(v.ID)">查看课程</el-button> -->
                    </div>
                  </div>
                </el-checkbox-group>
              </el-form-item>
              <el-form-item class="form-item">
                <el-button type="primary" size="default" @click="submitUpdateUserCourseGroup">保存</el-button>
              </el-form-item>
            </el-form>
          </div>
          <div class="container-right">
            <el-table class="container-right-table" width="100%" stripe :data="courseData">
              <template v-slot:empty>
                <el-empty image="https://cdn-hterobot.oss-cn-qingdao.aliyuncs.com/image/ojSass-empty.png" />
              </template>
              <el-table-column prop="name" label="课程名" width="">
                <template #header>
                  {{ courseGroupName }} - 课程
                </template>
                <template #default="{ row }">
                  {{ row.name }}
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ElMessage } from "element-plus";
import { computed, onMounted, ref, watch } from "vue";
import { useStore } from "vuex";
import {
  asyncGetAllCourseGroup,
  asyncaddUsercourse,
  asyncfindteamusergroup,
  asyncgetteam,
  asyncselectUsercourse,
  asyncselectcourse,
  asyncselectteamuser
} from "../../../api";
import { Storekey } from "../../../interface";
import Alymodel from "../../../mysql_interface/model";
import { default as Studycodemodel, default as study } from "../../../mysql_interface/studycodemodel";
import { courseCatebag } from "../data/data";

const courseGroupIds = courseCatebag.map(e => (e.ID))

const store = useStore(Storekey)
// 当前登录用户
const user = computed(() => {
  return store.state.user;
});
const teamId = computed(() => {
  return Number(user.value?.teamid);
});
const courseCfgDialogVisible = ref(false)
// 分页表格
const tableData = ref<Studycodemodel.Iteamuser[]>([]);
const count = ref(0);
const limit = ref(500)
const offset = ref(0)

const teamusergroupid = ref()
const selectGroup = computed(() => {
  return [{ ID: '全部', name: '全部' }, { ID: '未分组', name: '未分组' }, ...group.value]
})
const teamInfo = ref<Studycodemodel.Iteam>({})
const group = ref<Studycodemodel.Iteamusergroup[]>([])
async function getTeamGroupInfo() {
  // 获取团队信息
  teamInfo.value = await asyncgetteam({ ID: teamId.value });
  // 获取团队分组
  group.value = await asyncfindteamusergroup({ teamid: teamId.value });
  let groupId = teamusergroupid.value === '未分组' ? null : teamusergroupid.value
  // 获取团队成员
  let cond = { teamid: teamId.value, _limit: limit.value, _offset: offset.value, }
  if (groupId !== '全部') { cond.teamusergroupid = groupId }
  const data = await asyncselectteamuser(cond);
  tableData.value = data.rows;
  count.value = data.count;
}

// 设置课程
function setCourse() {
  courseCfgDialogVisible.value = true
  showCourseList(courseCatebag[0].ID)
  // 成员课程包回填
  formatterCourseGroupCheckbox()
}
const disabled = computed(() => {
  return !multipleSelection.value.length
})

// 弹窗复选框成员课程包回填
function formatterCourseGroupCheckbox() {
  if (multipleSelection.value?.length === 1) {
    const selectedUid = multipleSelection.value[0].userid
    matchCourseGroup(selectedUid, (g: AllCourseGroup) => {
      courses.value.push(g.ID)
    })
  }
}

// 多选
const multipleSelection = ref<Studycodemodel.Iteamuser[]>([])
function handleSelectionChange(v: Studycodemodel.Iteamuser[]) {
  multipleSelection.value = v
}
// 保存
async function submitUpdateUserCourseGroup() {
  await getAllCourseGroup()
  let user_ID = multipleSelection.value.map(e => (e.userid))
  // 删除
  let del_course_ID: number[] = []
  // 新增
  let add_course_ID: number[] = []

  allCourseGroup.value.forEach(item => {
    item.coursecatebag?.forEach(coursecatebag => {
      // 删除所有课程
      del_course_ID.push(coursecatebag.cid as number)
      // 匹配选中课程包，所有课程
      if (courses.value.find(e => e === item.ID)) {
        add_course_ID.push(coursecatebag.cid as number)
      }
    })
  })
  let usercourse: { user_ID: number, course_ID: number, permission: number, }[] = []
  user_ID.forEach(uid => {
    add_course_ID.forEach(cid => {
      usercourse.push({
        user_ID: uid as number,
        course_ID: cid,
        permission: 100
      })
    })
  })
  try {
    await asyncaddUsercourse({
      teamid: teamId.value,
      user_ID,
      course_ID: del_course_ID,
      usercourse,
    })
    ElMessage.success("操作成功");
    close()
    start()
  } catch (e: any) {
    ElMessage.error(e);
  }
}
// 课程包
const courses = ref<any[]>([])
async function start() {
  await getTeamGroupInfo()
  // 成员-课程
  getUsercourse()
  // 课包-课程
  getAllCourseGroup()
}
onMounted(() => {
  start()
})

// formatter
function formatGroupName(teamusergroupid: number) {
  const d = group.value?.find((v: study.Iteamusergroup) => v.ID == teamusergroupid);
  if (d) {
    return d.name;
  }
  return '未分组'
}
// 根据课程获取课程包
function formatCourseGroup(row: Studycodemodel.Iteamuser) {
  let str: (string | undefined)[] = []
  let userId = row.userid
  matchCourseGroup(userId, (g: AllCourseGroup) => {
    str.push(g.name)
  })
  return str.join("、")
}

// 利用课程和课包-课程 求交集
function matchCourseGroup(uid: number, fn: Function) {
  //  [{ ID: 193754, course_ID: 787, permission: 1, user_ID: 100007, }]
  let userCourse = userCourseMap.value[uid] || []
  allCourseGroup.value.forEach(g => {
    let coursecatebag = g.coursecatebag || []
    for (let i = 0; i < coursecatebag.length; i++) {
      let c = coursecatebag[i]
      let ret = userCourse.find(uc => uc.course_ID === c.cid)
      if (ret) {
        fn(g)
        break
      }
    }
  })
}

function pageChg(val: number) {
  offset.value = limit.value * (val - 1);
  start()
}

// 获取团队成员课程配置 user_ID - course_ID
const userCourseMap = ref<{ [uid: number]: Alymodel.IMusercourse[] }>({})
async function getUsercourse() {
  userCourseMap.value = await asyncselectUsercourse({
    teamid: teamId.value,
    user_ID: tableData.value.map(e => e.userid),
    _order: 'createtime'
  })
}
// 获取所有课程包-课程
interface AllCourseGroup extends Alymodel.IMcatebag { coursecatebag: Alymodel.IMcoursecatebag[] }
const allCourseGroup = ref<AllCourseGroup[]>([])
async function getAllCourseGroup(id: number[] = courseGroupIds) {
  const { rows, count } = await asyncGetAllCourseGroup({
    teamid: teamId.value,
    ID: id,
    // _order: "paixu",
    _order: "ID",
    _sortable: "ASC"
  })
  // 排序
  allCourseGroup.value = (rows as AllCourseGroup[])
}

// 单个课程包-课程
const hoveredCourseGroupID = ref()
const courseData = ref<Alymodel.IMcourse[]>([])
const courseGroupName = ref("")
function showCourseList(id: Number) {
  hoveredCourseGroupID.value = id
}
watch(hoveredCourseGroupID, async () => {
  const data = allCourseGroup.value.find(e => e.ID === hoveredCourseGroupID.value)
  if (data) {
    const cids = data.coursecatebag.map(e => e.cid)
    const { rows, count } = await asyncselectcourse({
      teamid: teamId.value, ID: cids,
      _limit: 1000,
      _order: "ID",
      _sortable: "ASC"
    })
    courseGroupName.value = data.name
    courseData.value = rows
  }
})


function close() {
  courseCfgDialogVisible.value = false
  courses.value = []
}
</script>

<style scoped>
.container-box {
  padding: 0 20px;
}

.container-content {
  display: flex;
  align-items: flex-start;
  justify-content: space-evenly;
  width: 100%;
  margin: 0;
  /* width: 60%; */
}

.form-item {
  margin: 20px;
  margin-bottom: 10px;
  display: flex;
  align-items: flex-start;
}

.form-item-check-box {
  flex: 0 0 auto;
  display: inline-block;
  width: 200px;
  line-height: 30px;
  font-size: 14px !important;
}

.desc {
  text-indent: 2rem;
  margin: 0 20px;
  margin-right: 0;
  font-size: 14px;
  color: #7f7f7f;
  /* width: 400px; */
  line-height: 30px;
}

.desc:hover {
  background: rgb(250, 250, 250);
  border-radius: 4px;
  /* color: #fff; */
}

.btn-box {
  line-height: 30px;
}

.container-right {
  width: 50%;
}

.container-right,
.container-right-table {
  height: calc(100vh - 200px);
}

.container-right-table {
  width: 100%;
}

.pager {
  margin-top: 10px;
  margin-right: 0;
  float: right;
}
</style>